package com.situ.controller;

import com.situ.bean.User;
import com.situ.service.IUserService;
import com.situ.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {
    @Autowired
    IUserService userService;

    @PostMapping("/upload-avatar")
    public ResponseEntity<Map<String, Object>> uploadAvatar(@RequestParam("avatar") MultipartFile file, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        if (file.isEmpty()) {
            response.put("success", false);
            response.put("message", "未选择文件");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

            // 保存文件到指定路径
            File dest = new File(SYS.FILE_UPLOAD_DIR + uniqueFileName);
            file.transferTo(dest);

            // 返回文件名
            response.put("success", true);
            response.put("filename", uniqueFileName);

            //将文件夹中的文件名保存到session中，用于在页面中显示头像
           User user = (User) session.getAttribute(SYS.UPLOAD_USER);
           user.setImgurl(uniqueFileName);
           session.setAttribute(SYS.UPLOAD_USER, user);
           //刷新静态资源在项目中的状态




           if( userService.updateUser(user)){
               System.out.println("头像上传成功");

           }

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "文件上传失败");
            return ResponseEntity.internalServerError().body(response);
        }


    }
}